const superagent = require('superagent');
var settings = require('../settings');
var log = require('../utils/logs').getLogger();

exports.authUser = function (req, res, next) {
  var token = req.get("authentication")
  if (token) {
    var noAuth = false
    for (var i = 0; i < settings.AUTH.EXCLUDES.length; i++) {
      if (settings.AUTH.EXCLUDES[i].test(req.path)) {
        noAuth = true
        break;
      }
    }
    if (noAuth) {
      req.user = {
        is_authenticated: false
      }
      return next();
    }
    superagent
      .get(settings.AUTH.BASE_URL + settings.AUTH.URL_GET_VISITOR_INFO)
      .set('Authentication', token)
      .set('Accept', 'application/json, text/plain, */*')
      .end((err, result) => {
        if (err) {
          log.error(err)
          req.user = {
            is_authenticated: false
          }
          return next();
        }
        if (result.body.status === 'success') {
          req.user = result.body.data;
          req.user.is_authenticated = true
        } else {
          req.user = {
            is_authenticated: false
          }
        }
        return next();
      })
  } else {
    req.user = {
      is_authenticated: false
    }
    return next();
  }
};
